package com.atguigu.msmservice.controller;

import com.atguigu.msmservice.service.MsmService;
import com.atguigu.commonutils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @create: 2022/10/7
 * @Description:
 * @FileName: MsmController
 * @自定义内容：
 */
@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送邮箱验证码
    @GetMapping("sendEmail/{email}")
    public R sendEmail(@PathVariable String email) {
        //从redis获取验证码，如果获取到，返回ok
        //key 手机号 value 验证码
        String code = (String) redisTemplate.opsForValue().get(email);
        if (!StringUtils.isBlank(code)) {
            return R.ok();
        }

        //如果从redis获取不到，进行邮箱发送
        //生成随机验证码，传递邮箱进行发送
        code = msmService.getCode();

        //调用service发送验证码的方法
        boolean isSend = msmService.sendEmail(email, code);
        if (isSend){
            //如果发送成功，把发送成功的验证码放到redis里面
            //设置有效时间
            // set(邮箱地址, 验证码, 有效时间, 时间单位（分钟）);
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }
    }

}
